package com.xingqing.controller;

import com.xingqing.domain.vo.Result;
import com.xingqing.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping
    public Result<String> upload(@RequestParam("file") MultipartFile file,
                                @RequestParam(value = "type", defaultValue = "image") String fileType) {
        log.info("文件上传，文件名: {}，类型: {}", file.getOriginalFilename(), fileType);

        // 检查文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("文件不能为空");
        }
        
        try {
            String fileUrl = fileStorageService.upload(file, fileType);
            log.info("文件上传成功，访问路径: {}", fileUrl);
            return Result.success(fileUrl);
            
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new com.xingqing.exception.FileUploadException("文件上传失败: " + e.getMessage(), e);
        }
    }

    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("头像上传，文件名: {}", file.getOriginalFilename());
        
        // 检查文件是否为空
        if (file.isEmpty()) {
            log.warn("上传文件为空");
            return Result.error("头像文件不能为空");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            log.warn("文件类型不正确: {}", contentType);
            return Result.error("只能上传图片文件");
        }
        
        // 检查文件大小（限制5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            log.warn("文件大小超出限制: {} bytes", file.getSize());
            return Result.error("图片大小不能超过5MB");
        }
        
        try {
            String fileUrl = fileStorageService.upload(file, "avatars");
            log.info("头像上传成功，访问路径: {}", fileUrl);
            return Result.success(fileUrl);
            
        } catch (Exception e) {
            log.error("头像上传失败", e);
            throw new com.xingqing.exception.FileUploadException("头像上传失败: " + e.getMessage(), e);
        }
    }
}